<template>
  <view class="water-fall" :style="{ padding: gap / 2 + 'rpx', minHeight: minHeight+'px' }">
    <template v-if="list.length">
      <view v-for="(wItem, wIndex) in waterList" :id="'waterColumn' + wIndex" :key="wIndex" class="water-column" :style="{ width: 100 / columns + '%', padding: gap / 2 + 'rpx' }">
        <view v-for="(item, index) in wItem.list" :key="index" class="water-fall-item">
          <slot :item="item" :column-index="wIndex" :index="index" :list="totalList"></slot>
          <!-- 以下代码主要是更精确的处理rpx到px的转换问题 -->
          <view :style="{ paddingBottom: gap/2 + 'rpx' }"></view>
          <view :style="{ paddingBottom: gap/2 + 'rpx' }"></view>
        </view>
      </view>
    </template>
    <slot name="footer"></slot>
  </view>
</template>
<script>
export default {
  name: 'WaterFall',
  props: {
    list: { type: Array, default: () => [] },
    columns: { type: Number, default: 2 },
    gap: { type: [Number, String], default: 20 },
    minHeight: { type: Number, default: 0 },
    delay: { type: Number, default: 200 }
  },
  data() {
    return {
      totalList: [],
      waterList: []
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.totalList = []
      this.waterList = []
      for (let i = 0; i < this.columns; i++) {
        this.waterList.push({
          height: 0,
          list: []
        })
      }
      this.$nextTick(() => {
        if (this.list && this.list.length) {
          this.addToList(this.list)
        }
      })
    },
    addToList(data, index = 0) {
      let wIndex = 0
      const height = this.waterList[0].height
      for (let i = 1; i < this.waterList.length; i++) {
        if (this.waterList[i].height < height) {
          wIndex = i
        }
      }
      // console.log(wIndex)
      this.totalList.push(data[index])
      this.waterList[wIndex].list.push({
        ...data[index],
        realIndex: this.totalList.length - 1
      })

      let timer
      this.$nextTick(() => {
        timer = setTimeout(() => {
          const query = uni.createSelectorQuery().in(this)
          query
            .select('#waterColumn' + wIndex)
            .boundingClientRect(res => {
            // console.log('#waterColumn' + wIndex, res.height)
              this.waterList[wIndex].height = res.height
              if (index + 1 < data.length) {
                this.addToList(data, index + 1)
              } else {
                clearTimeout(timer)
              }
            })
            .exec()
        }, this.delay)
      })
    }
  }
}
</script>
<style lang="scss">
.water-fall {
  .water-column {
    box-sizing: border-box;
    display: inline-block;
    vertical-align: top;

    .water-fall-item{
      position: relative;
    }
  }
}
</style>
